<template>
  <div>
    <div v-if="formType === 1">
      <div class="clearfix">
        <a-upload :file-list="fileList" list-type="picture-card" disabled>
          <div v-if="fileList.length < setting.options.length">
            <PlusOutlined />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </div>
    </div>
    <div v-else>
      <div v-if="setting.fieldState === 0">
        <div class="clearfix">
          <a-upload
            :file-list="fileList"
            @change="hangchange"
            list-type="picture-card"
            @preview="handlePreview"
            :remove="handleRemove"
            :before-upload="beforeUpload"
            :disabled="setting.options.disabled"
          >
            <div v-if="fileList.length < setting.options.length">
              <PlusOutlined />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </div>
      </div>
      <div v-else>
        <a-upload
          :file-list="fileList"
          list-type="picture-card"
          disabled
        ></a-upload>
      </div>
    </div>
    <!-- 图片预览 -->
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="previewVisible = false"
    >
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
  import { GetUrlList, Upload } from '@/api/upload/api'
  import lrz from 'lrz'
  import { PlusOutlined } from '@ant-design/icons-vue'

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }
  export default {
    components: {
      PlusOutlined,
    },
    data() {
      return {
        previewVisible: false,
        previewImage: '',
        fileList: [],
        uploadfileList: [],
        uploading: false,
        isUpload: true,
        dataModel: this.models[this.setting.table + '-' + this.setting.field],
      }
    },
    props: {
      formType: {
        type: Number,
        default: 0,
      },
      setting: {
        type: Object,
        default: null,
      },

      models: {
        type: Object,
        default: Object,
      },
    },

    mounted() {
      this.load()
    },

    methods: {
      //  初始化文件
      load() {
        this.fileList = []
        if (this.dataModel !== '') {
          var queryData = {
            ids: this.dataModel,
          }
          GetUrlList(queryData).then((res) => {
            console.log('res', res)
            if (res.isSuccess) {
              res.content.forEach((element) => {
                this.fileList.push({
                  uid: element.id,
                  name: element.expectedFileName,
                  status: 'done',
                  url: element.downloadUrl,
                })
              })
            }
          })
        }
      },

      // 图片预览
      async handlePreview(file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 图片删除
      handleRemove(file) {
        this.isUpload = false
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
        var photoIds = ''
        this.fileList.forEach((element) => {
          photoIds += element.uid + ','
        })
        this.models[this.setting.table + '-' + this.setting.field] = photoIds
      },
      // 文件上传之前的限制
      beforeUpload(file) {
        this.isUpload = true
        this.uploadfileList = [...this.uploadfileList, file]
        const isJpgOrPng =
          file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.isUpload = false
          this.$message.error('只允许上传jpg和png类型的图片!')
        }

        return false
      },
      // 第二种,图片大小超过4M,长度超过2000就压缩
      beforeUpload2(file) {
        // 图片不大于4m,宽度不大于2000
        return new Promise((resolve, reject) => {
          const _URL = window.URL || window.webkitURL
          // 这里需要计算出图片的长宽
          const img = new Image()
          img.onload = function () {
            // 压缩组件
            lrz(file, {
              width: 1024,
              height: 1024,
              quality: 0.9,
            })
              .then(function (rst) {
                // blob类型转file类型
                const files = new window.File([rst.file], file.name, {
                  type: file.type,
                })
                resolve(files)
              })
              .always(function () {
                // 不管成功或失败，都会执行
              })
          }
          // 需要把图片赋值
          img.src = _URL.createObjectURL(file)
        })
      },
      hangchange({ fileList }) {
        var that = this
        if (this.isUpload) {
          // ---------------------
          this.uploading = true
          const { uploadfileList } = this
          var length = uploadfileList.length - 1
          this.beforeUpload2(uploadfileList[length]).then((res) => {
            console.log('file', res)
            const formData = new FormData()
            formData.append('fileContainerName', 'default')
            formData.append('fileType', 2)
            formData.append('ownerUserId', '')
            formData.append('generateUniqueFileName', false)
            formData.append('file', res)
            Upload(formData)
              .then((res) => {
                console.log('uploadres', res)
                var element = res.content.downloadInfo
                that.fileList.push({
                  uid: res.content.fileInfo.id,
                  name: element.expectedFileName,
                  status: 'done',
                  url: element.downloadUrl,
                })
                that.$message.success('文件上传成功')
                var photoIds = ''
                that.fileList.forEach((element) => {
                  photoIds += element.uid + ','
                })
                this.models[
                  this.setting.table + '-' + this.setting.field
                ] = photoIds
              })
              .finally(() => {
                that.uploading = false
              })
          })
        }
      },
    },
  }
</script>

<style>
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
